var playerID = -1;
var gameID = -1;

var AjaxRequest = {
	receiveGameList : null,
	
	init : function() {
		$('#game .create-game').bind('click', function() {
			AjaxRequest.createGame();
		});
		
		$("#lobby a").live('click', function() {
			AjaxRequest.cancelGetGameList();
		});
	},
		
	createGame : function() {
		$.post('GameControl', {
			'action':'createGame'
		}, function(response) {
			AjaxRequest.cancelGetGameList(); 
			var data = $.parseJSON(response);
			window.location = 'game.jsp';
		});
	},
	
	newPlayer : function() {
		$.post('GameControl', {
			'action':'newPlayer'
		}, function (data) {
			playerID = parseInt(data);
		});
	},
	
	getPlayerID : function() {
		$.post('GameControl', {
			'action':'getPlayerId'
		}, function (data) {
			playerID = parseInt(data);
			AjaxRequest.getGameID();
		});
	},
	
	getGameID : function() {
		$.post('GameControl', {
			'action':'getGameId'
		}, function (data) {
			gameID = parseInt(data);
		});
	},
	
	uploadFleets : function() {
		var gameStarted = false;
		
		for (placed in placedFleets) {
			var jsonFleets = {
				"action" : "addFleets",
				"playerID" : String(playerID),
				"id" : String(placedFleets[placed].id),
				"size" : String(placedFleets[placed].size),
				"top" : String(placedFleets[placed].top),
				"left" : String(placedFleets[placed].left),
				"orientation" : String(placedFleets[placed].orientation)
			};
			
			$.post('GameControl', jsonFleets);
		}
		
//		$.post('GameControl', {
//			'action': 'getGameStatus'
//		}, function (data) {
//			var response = $.parseJSON(data);
//			
//			if (response.gameStarted == "1") {
				AjaxRequest.updateTurn();
//			}
//		});
	},
	
	updateTurn : function() {
		$.post('GameControl', {
			'action':'getTurn',
			'playerID':String(playerID),
			'gameID':String(gameID)
		}, function(data) {
			canFire = true;
			var gameStatus = $.parseJSON(data);
			
			if (gameStatus.myTurn == "true") {
				whosTurn = 1;
			} else if (gameStatus.myTurn == "false") {
				whosTurn = 0;
			}
			
			canvas.displayWhosTurn();

			if (gameStatus.enemyLeft == "1" || gameStatus.winner != "-1") {	
				if (gameStatus.enemyLeft == "1") {
					canvas.displayEnemyLeft();
				}
				
				if (gameStatus.winner != "-1") {
					if (gameStatus.winner == playerID) {
						alert("Palju õnne! Sina võitsid");
					} else {
						alert("Kahjuks sa kaotasid :(");
					}
					gameEnded = true;
				}

			}
			var t = setTimeout("AjaxRequest.getEnemyShot()", 200);		
			
		});
	},
	
	getEnemyShot : function() {
		$.post('GameControl', {
			"action" : "getEnemyShot",
            "playerID" : String(playerID),
            "gameID" : String(gameID)
		}, function(data) {
			var enemyShot = $.parseJSON(data);

			if (enemyShot.result != "-1") {
				var x = parseInt(enemyShot.x);
				var y = parseInt(enemyShot.y);
				
				if (enemyShot.result == "0") {
					canvas.drawShot("missed", null, x, y, "player");
					shotsForLocalStorage["BSHIPS_" + String(localGameId) + "_" + String(player.total + enemy.total)] = String(x) + "_" + String(y) + "_enemy_0";
					Sound.playMissed();
				}
				
				if (enemyShot.result == "1") {
					canvas.drawShot("hit", "hit", x, y, "player");
					shotsForLocalStorage["BSHIPS_" + String(localGameId) + "_" + String(player.total + enemy.total)] = String(x) + "_" + String(y) + "_enemy_1";
					Sound.playHit();
					enemy.hit++;
				}
				
				if (enemyShot.result == "2") {
					var id = enemyShot.id;
					enemy.sinked++;
					canvas.displayScore("enemy", enemy.sinked);
					canvas.removeHitShots("hit", placedFleets["fleet"+ enemyShot.id]);
					canvas.drawFleet("sinkedEnemyFleet", "sinked", placedFleets["fleet"+ enemyShot.id], "player");
					shotsForLocalStorage["BSHIPS_" + String(localGameId) + "_" + String(player.total + enemy.total)] = String(x) + "_" + String(y) + "_enemy_2_" + String(id);
					Sound.playSinked();
					enemy.hit++;
				}
				enemy.total++;
			}
			
			if ((gameEnded == true)) {
				Replay.uploadDataToLocalStorage();
				shotsForLocalStorage = [];
				clearTimeout(f);
				f = null;
			} else {
				var f = setTimeout("AjaxRequest.updateTurn()", 200);
			}
			
		});
	},
	
	turnComplete : function() {
		$.post('GameControl', {
			'action':'turnComplete',
			'gameID':String(gameID)
		});
	},
	
	shoot : function(x, y) {
		$.post('GameControl', {
			'action':'shoot',
			'id':String(playerID),
			'x':String(x),
			'y':String(y)
		}, function(data) {
			var outcome = $.parseJSON(data);
			
			if(outcome.result == 0){
				Sound.playMissed();
				canvas.drawShot("missed", null, x, y, "enemy");
				shotsForLocalStorage["BSHIPS_" + String(localGameId) + "_" + String(player.total + enemy.total)] = String(x) + "_" + String(y) + "_player_" + String(outcome.result);
				/* Switch turn only if we have missed the shot*/
				AjaxRequest.turnComplete();
			} else if(outcome.result == 1){
				Sound.playHit();
				canvas.drawShot("hit", "enemyHit", x, y, "enemy");
				shotsForLocalStorage["BSHIPS_" + String(localGameId) + "_" + String(player.total + enemy.total)] = String(x) + "_" + String(y) + "_player_" + String(outcome.result);
				player.hit++;
			} else if(outcome.result == 2){
				Sound.playSinked();
				player.sinked++;
				var tempfleet = new Fleet(parseInt(outcome.id), parseInt(outcome.size), "temp");
				tempfleet.orientation = parseInt(outcome.orientation);
				tempfleet.setTopLeft(parseInt(outcome.top), parseInt(outcome.left));
				canvas.displayScore("player", player.sinked);
				canvas.removeHitShots("enemyHit", tempfleet);
				canvas.drawFleet("sinkedEnemyFleet", "sinked", tempfleet, "enemy");
				shotsForLocalStorage["BSHIPS_" + String(localGameId) + "_" + String(player.total + enemy.total)] = String(x) 
				+ "_" + String(y) + "_player_" + String(outcome.result) + "_" + String(outcome.id) 
				+ "_" + String(outcome.size) + "_" + String(outcome.top) + "_" + String(outcome.left) 
				+ "_" + String(outcome.orientation);

				player.hit++;
			}		
			player.total++;		
		});
	},
	
	getGameList : function() {
		$.post('GameControl', {
			'action':'getGameList'
		}, function(response) {
			$("#gameList").empty();
			var data = $.parseJSON(response);
			var games = data.games;
			if (games.length > 0) {
				for (var id in games) {
					
					/* Display all games which is started and which is played at the moment */
					if (games[id].status == 0 || games[id].status == 1) {
						if (games[id].count < 2) {
							$("#gameList").append("<li><a href='GameControl?action=joinGame&gameId=" + games[id].id + "'>" + games[id].creator +" ("+ games[id].count +  ")</a></li>");
						} else {
							$("#gameList").append("<li class='full'>" + games[id].creator +" (" + games[id].count +  ")</li>");
						}
					}
				}
			}
			
		});
		
		if (AjaxRequest.receiveGameList != null) {
			clearTimeout(AjaxRequest.receiveGameList);
		}
		
		AjaxRequest.receiveGameList = setTimeout("AjaxRequest.getGameList()", 5000);
	},
	
	cancelGetGameList : function() {
		if (AjaxRequest.receiveGameList != null) {
			clearTimeout(AjaxRequest.receiveGameList);
		}
	},
	
	getLeaderBoard : function() {
		$.get('GameControl?action=getLeaderBoard',
			function(response) {
			
				console.log(response);
				$('tr .player-information').remove();
				var players = $.parseJSON(response);
				var index = 1;
				for (var player in players) {
					var playerInformation = '<tr class="player-information"><td class="number">' + index + '</td><td>' + players[player].name + '</td><td>' + players[player].wins + '</td><td>' + players[player].losses + '</td></tr>';
					$('.list').append(playerInformation);
					index++;
				}
		});
	}
};

window.onbeforeunload = unLoadPage;

function unLoadPage() {
	
	if (String(window.location).indexOf('game.jsp') != -1) {
		$.post('GameControl', {
			'action': 'enemyLeft'
		});
	}
}